// VBConversions Note: VB project level imports
using System.Data;
using DevExpress.XtraEditors.Controls;
using System.Diagnostics;
using System.Xml.Linq;
using DevExpress.XtraEditors.Repository;
using System.Collections.Generic;
using System.Data.SqlClient;
using Microsoft.VisualBasic;
using System.Configuration;
using System.Collections;
using DevExpress.XtraEditors;
using System.Data.Sql;
using Microsoft.SqlServer;
using System.Windows.Forms;
using System;
using DevExpress.XtraReports;
using Microsoft.SqlServer.Management.Smo;
using DevExpress;
using System.Linq;
using System.IO;
// End of VB project level imports

using System.Text;
using DevExpress.XtraReports.UI;

/// <summary>
///
/// </summary>
/// <remarks>Should GO in WinFormExt not in CommonExt... Dependency on DevExp component - AL 2013-06-03 </remarks>
namespace SCIEF.SysBFW.CommonExt
{
	public class RptNotification
	{
		
		/// <summary>
		/// Get The Report Definition from the database
		/// </summary>
		/// <param name="reportName"></param>
		/// <returns></returns>
		/// <remarks>Make sure the Reportname is unique in the table Metatrings (We use StringCD to store the reportName)</remarks>
		public static XtraReport GetReportFromDB(string reportName)
		{
			XtraReport report = null;
			Guid dataFormat;
			byte[] binaryString = null;
			
			
			using (MetaQuery mqReport = MetaQuery.GetMetaQueryByName("ReadReportFromDocTemplate"))
			{
				mqReport.SQLWhere = string.Format("Name = \'{0}\' ", reportName);
				mqReport.FillResultQuery();
				//
				if (mqReport.ResultQuery.Rows.Count == 1)
				{
					string reportString = mqReport.ResultQuery.Rows[0]["Data"].ToString();
					
					if (mqReport.ResultQuery.Rows[0]["BinaryData"] != DBNull.Value)
					{
						binaryString = (byte[]) (mqReport.ResultQuery.Rows[0]["BinaryData"]);
						dataFormat = (Guid) (mqReport.ResultQuery.Rows[0]["DataFormatId_FK"]);
						
						if (dataFormat != null&& dataFormat == Base.IdRepository.APP_DATAFORMAT_UTF8)
						{
							report = LoadDocument_UsingUTF8(binaryString);
							
						}
						else if (dataFormat != null&& dataFormat == Base.IdRepository.APP_DATAFORMAT_BIN)
						{
							LoadDocument(binaryString);
						}
						
					}
					else if (!string.IsNullOrEmpty(reportString))
					{
						//OUSTANDINGISSUE: ancien code qui permet de lire la colonne Data(varchar). On le garde tant qu'on n'a pas converti en varbinary. clieng 2013-01-22.
						byte[] data = null;
						UTF8Encoding encoder = default(UTF8Encoding);
						reportString = mqReport.ResultQuery.Rows[0]["Data"].ToString();
						using (MemoryStream msXmlReportLayout = new MemoryStream())
						{
							encoder = new UTF8Encoding();
							report = new XtraReport();
							//
							data = encoder.GetBytes(reportString);
							msXmlReportLayout.Write(data, 0, data.Length);
							//
							report.LoadLayoutFromXml(msXmlReportLayout);
						}
						
					}
					else
					{
						report = new XtraReport();
						report.Name = reportName;
						//report.DataSourceSchema
					}
					
				}
			}
			
			return report;
		}
		
		/// <summary>
		/// Save a Report Definition in the database
		/// Table use MetaStrings
		/// </summary>
		/// <param name="report"></param>
        /// <param name="documentTemplateID"></param>
        /// <param name="categoryID"></param>
        /// <param name="typeID"></param>
        /// <param name="classID"></param>
        /// <param name="dataFormatID"></param>
        /// <param name="queryID"></param>
		/// <returns></returns>
		/// <remarks>Make sure the Reportname is unique in the table Metatrings (We use StringCD to store the reportName)</remarks>
		public static bool SaveReportInDB(XtraReport report, Guid documentTemplateID, Guid categoryID, Guid typeID, Guid classID, Guid dataFormatID, Guid queryID)
		{
			SqlCommand sqlcmd = null;
			
			Guid default_ClassID = CommonExt.Base.IdRepository.APP_DOCTEMPLATECLASS_RPT;
			Guid default_CategoryID = CommonExt.Base.IdRepository.APP_DOCTEMPLATECATEGORY_REPORT;
			Guid default_TypeID = CommonExt.Base.IdRepository.APP_DOCTEMPLATETYPE_REPX;
			Guid default_DataFormatID = CommonExt.Base.IdRepository.APP_DATAFORMAT_UTF8;
			
			using (MemoryStream reportStream = new MemoryStream())
			{
				try
				{
					//pour le sauver dans la BD. Le Format xml semble plus petit a date - aleblanc 2012-12-16
					//report.Tag = Nothing
					report.SaveLayoutToXml(reportStream);
					reportStream.Position = 0;
					
					using (StreamReader streamReader = new StreamReader(reportStream))
					{
						
						sqlcmd = MetaQuery.GetSPCmdByMetaName("ReportBuilder_Save");
						sqlcmd.Parameters["@DocumentTemplateId"].Value = documentTemplateID;
						sqlcmd.Parameters["@CategoryId_FK"].Value = (Guid.Empty.Equals(categoryID)) ? default_CategoryID : categoryID;
						sqlcmd.Parameters["@TypeId_FK"].Value = (Guid.Empty.Equals(typeID)) ? default_TypeID : typeID;
						sqlcmd.Parameters["@ClassId_FK"].Value = (Guid.Empty.Equals(classID)) ? default_ClassID : classID;
						sqlcmd.Parameters["@Name"].Value = report.Name;
						sqlcmd.Parameters["@Description"].Value = report.Name;
						sqlcmd.Parameters["@Description_ALT"].Value = report.Name;
						sqlcmd.Parameters["@DataFormatId_FK"].Value = (Guid.Empty.Equals(dataFormatID)) ? default_DataFormatID : dataFormatID;
						sqlcmd.Parameters["@BinaryData"].Value = reportStream.ToArray();
						sqlcmd.Parameters["@QueryID_FK"].Value = (Guid.Empty.Equals(queryID)) ? Guid.Empty  : queryID;
						
						
						//sqlcmd.Parameters("@Data").Value = streamReader.ReadToEnd
						//If queryID = Guid.Empty Then
						//    sqlcmd.Parameters("@QueryID_FK").Value = DBNull.Value
						//Else
						//    sqlcmd.Parameters("@QueryID_FK").Value = queryID
						//End If
						
						sqlcmd.ExecuteNonQuery();
					}
					
				}
				catch (Exception ex)
				{
					throw (ex);
				}
				finally
				{
					if (sqlcmd != null)
					{
						sqlcmd.Connection.Close();
						sqlcmd.Dispose();
					}
				}
			}
			
			return true;
		}
		
		public static XtraReport LoadDocument_UsingUTF8(byte[] binaryString)
		{
			string reportString = default(string);
			XtraReport report = null;
			byte[] data = null;
			UTF8Encoding encoder = default(UTF8Encoding);
			try
			{
				using (MemoryStream msXmlReportLayout = new MemoryStream())
				{
					encoder = new UTF8Encoding();
					report = new XtraReport();
					//
					reportString = Encoding.UTF8.GetString(binaryString);
					data = encoder.GetBytes(reportString);
					msXmlReportLayout.Write(data, 0, data.Length);
					//
					report.LoadLayoutFromXml(msXmlReportLayout);
				}
				
			}
			catch (Exception ex)
			{
				throw (ex);
			}
			return report;
		}
		
		public static void LoadDocument(byte[] binaryString)
		{
			
			//Using fStream As New FileStream("C:\Injurie Copy.pdf", FileMode.CreateNew)
			//    Dim bw As New BinaryWriter(fStream)
			//    bw.Write(binaryString)
			//    bw.Close()
			//    fStream.Close()
			//End Using
			
			//byte[] binaryString = (byte[])reader[1];
			
			// // if the original encoding was ASCII
			// string x = Encoding.ASCII.GetString(binaryString);
			
			// // if the original encoding was UTF-8
			// string y = Encoding.UTF8.GetString(binaryString);
			
			// // if the original encoding was UTF-16
			// string z = Encoding.Unicode.GetString(binaryString);
		}
		
		
		public static byte[] EncodingObject(object obj, Guid dataFormatID)
		{
			byte[] binaryString = null;
			
			if (dataFormatID == Base.IdRepository.APP_DATAFORMAT_UTF8)
			{
				//
				if ((obj) is XtraReport)
				{
					XtraReport aReport = obj as XtraReport;
					UTF8Encoding encoder = new UTF8Encoding(true);
					string reportString = default(string);
					
					using (MemoryStream reportStream = new MemoryStream())
					{
						aReport.SaveLayoutToXml(reportStream);
						
						using (StreamReader streamReader = new StreamReader(reportStream))
						{
							reportString = streamReader.ReadToEnd();
							binaryString = encoder.GetBytes(reportString);
						}
						
					}
					
					
				}
			}
			else if (dataFormatID == Base.IdRepository.APP_DATAFORMAT_BIN)
			{
			}
			
			//string myStr = "";
			//using (MemoryStream ms = new MemoryStream()){
				//report.SaveLayout(ms,true);
				//ms.Seek(0, SeekOrigin.Begin);
				//StreamReader sr = new StreamReader(ms);
				//myStr = sr.ReadToEnd();
				
				
				
				return binaryString;
			}
		}
		
	}
